import { Context } from 'egg';

const RESULT = Symbol('Context#result');

export default {
  get result() {
    if (!this[RESULT]) {
      this[RESULT] = { success: false };
    }
    return this[RESULT];
  },

  set result(rst) {
    this[RESULT] = rst;
  },

  setSuccess(success = true) {
    this.result.success = success;
  },

  setMessage(msg: any) {
    this.result.message = msg;
  },

  setData(data: any) {
    this.result.data = data;
  },

  setField(field: string, data: any) {
    this.result[field] = data;
  },

  setFields(fields: {[key: string]: any}) {
    Object.assign(this.result, fields);
  },

  sendResult(this: Context): void {
    this.result.message = this.result.success ? this.result.message || '200 ok!' :
    this.result.message || 'unknow error!';
    this.body = this.result;
  },

  sendSuccess(this: Context, successMsg: string = '200 ok!'): void {
    this.result.success = true;
    this.result.message = this.result.message || successMsg;
    this.body = this.result;
  },

  sendError(this: Context, msg: string = 'unknow error!'): void {
    this.result.message = msg;
    this.body = this.result;
  },

  send403(this: Context): void {
    this.status = 403;
    this.result.message = '403 Forbidden!';
    this.body = this.result;
  },

  send500(this: Context): void {
    this.status = 500;
    this.result.message = '500 Internal Server Error';
    this.body = this.result;
  },
};
